#include "StdAfx.h"
#include "DeviceManager.h"
#include "stdlis.h"

DeviceManager::DeviceManager(void)
{
}


DeviceManager::~DeviceManager(void)
{
	_DeviceList.clear();
}

HRESULT DeviceManager::Add(shared_ptr<Device> device)
{
	HRESULT hr = S_OK;
	if (Exist(device))
		return E_INVALIDARG;
	_DeviceList.push_back(device);
	return hr;
}

HRESULT DeviceManager::Remove(shared_ptr<Device> device)
{
	HRESULT hr;
	for (DeviceList::iterator it = _DeviceList.begin(); it != _DeviceList.end(); it++)
	{
		if (*it == device)
		{
			_DeviceList.erase(it);
			shared_ptr<Device> lookup = *it;
			CHECKHR(lookup->Uninit());
			return S_OK;
		}
	}
	return S_OK;
}

HRESULT DeviceManager::RemoveAll(void)
{
	HRESULT hr;
	while (_DeviceList.size() > 0)
	{
		shared_ptr<Device> device = _DeviceList.front();
		_DeviceList.erase(_DeviceList.begin());
		hr = device->Uninit();
		ASSERT(hr == S_OK);
	}
	return S_OK;
}

BOOL DeviceManager::Exist(shared_ptr<Device> device)
{
	for (DeviceList::iterator it = _DeviceList.begin(); it != _DeviceList.end(); it++)
	{
		if (*it == device)
			return true;
	}

	return false;
}

HRESULT DeviceManager::InitAllDevices(void)
{
	HRESULT hr = S_OK;
	for (DeviceList::iterator it = _DeviceList.begin(); it != _DeviceList.end(); it++)
	{
		if (*it == NULL)
			continue;
		CHECKHR((*it)->Init());
		ASSERT((*it)->IsInitialized());
	}
	return hr;
}

HRESULT DeviceManager::UninitAllDevices(void)
{
	HRESULT hr = S_OK;
	for (DeviceList::iterator it = _DeviceList.begin(); it != _DeviceList.end(); it++)
	{
		if (*it == NULL)
			continue;
		CHECKHR((*it)->Uninit());
		ASSERT((*it)->IsInitialized() == FALSE);
	}
	return hr;
}
